package bjut.core.singleton;

import bjut.core.bean.FactoryBean;
import bjut.core.exception.BeansException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/26 20:42
 */
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {

    public final Map<String, Object> singletonFactoryBeanObjectCache = new ConcurrentHashMap<>();

    protected Object getCachedObjectForSingletonFactoryBean(String beanName) {
        Object object = singletonFactoryBeanObjectCache.get(beanName);
        return object == NULL_OBJECT ? null : object;
    }

    protected Object getObjectFromFactoryBean(FactoryBean factoryBean, String beanName) {

        if (factoryBean.isSingleton()) {

            Object object = singletonFactoryBeanObjectCache.get(beanName);
            if (object == null) {
                object = doGetObjectFromFactoryBean(factoryBean, beanName);
                this.singletonFactoryBeanObjectCache.put(beanName, object);
            }
            return object == NULL_OBJECT ? null : object;
        } else {
            return doGetObjectFromFactoryBean(factoryBean, beanName);
        }

    }

    private Object doGetObjectFromFactoryBean(final FactoryBean factoryBean, final String beanName) {

        try {
            return factoryBean.getObject();
        } catch (Exception e) {
            throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation", e);
        }

    }


}
